<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 基础控制器扩展
 * 提供统一的成功响应和刷新功能
 */
class BaseController extends Backend
{
    /**
     * 成功响应并刷新列表
     * @param string $msg 提示信息
     * @param string $url 跳转地址
     * @param array $data 返回数据
     * @param int $wait 等待时间
     * @param array $header 头部信息
     */
    protected function successWithRefresh($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        // 默认添加刷新指令
        if (is_array($data)) {
            $data['refresh'] = true;
        } else {
            $data = ['refresh' => true];
        }
        
        return $this->success($msg, $url, $data, $wait, $header);
    }
    
    /**
     * 重写添加方法，自动添加刷新
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->successWithRefresh('添加成功');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
    /**
     * 重写编辑方法，自动添加刷新
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->successWithRefresh('编辑成功');
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 重写删除方法，自动添加刷新
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->successWithRefresh('删除成功');
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 重写批量操作方法，自动添加刷新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            $params = $this->request->post("params");
            try {
                if (is_array($list)) {
                    foreach ($list as $index => $item) {
                        if ($params) {
                            parse_str($params, $values);
                            $item->allowField(true)->save($values);
                        } else {
                            $count += $item->delete();
                        }
                    }
                }
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($count || $params) {
                $this->successWithRefresh('操作成功');
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}